<?php
/*
function config
function dit
function exec
function flush
function get
function init
function post
function setheader
function setopt

占位
.#.#.#.#.#.#.#.#.#.#*/
//占位
class class_curl
{
	var $data;
	var $error;
	var $setopt = array();
	var $timeout = 10;
	
	var $count = 0;
	var $cookiefile = '';
//-------------------------------------------------------------------------------
//$assoc是array('username' => '李宁', 'password' => '123')
//$files是array('imgs[]' => $path)
	function postfile($url, $files, $assoc = array())
	{
		static $disallow = array("\0", "\"", "\r", "\n");
		
		if(!is_array($files))
				$files = array('upfile' => $files);
		
		foreach($assoc as $k => $v)
		{
		  $k = str_replace($disallow, "_", $k);
		  $body[] = implode("\r\n", array(
		      "Content-Disposition: form-data; name=\"{$k}\"",
		      "",
		      filter_var($v),
		  ));
		}
		
		foreach($files as $k => $v)
		{
		  switch(true)
		  {
		      case false === $v = realpath(filter_var($v)):
		      case !is_file($v):
		      case !is_readable($v):
		          continue; // or return false, throw new InvalidArgumentException
		  }
		  
		  $data = file_get_contents($v);
		  $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
		  $k = str_replace($disallow, "_", $k);
		  $v = str_replace($disallow, "_", $v);
		  $body[] = implode("\r\n", array(
		      "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
		      "Content-Type: application/octet-stream",
		      "",
		      $data,
		  ));
		}
		
		do
		{
		  $boundary = "---------------------" . md5(mt_rand() . microtime());
		}
		while(preg_grep("/{$boundary}/", $body));
		
		array_walk($body, function(&$part) use ($boundary) { $part = "--{$boundary}\r\n{$part}"; });
		
		$body[] = "--{$boundary}--";
		$body[] = "";

		$set = array(
			CURLOPT_TIMEOUT        => $this->timeout,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_URL => $url,
		  CURLOPT_POST       => true,
		  CURLOPT_POSTFIELDS => implode("\r\n", $body),
		  CURLOPT_HTTPHEADER => array(
		      "Expect: 100-continue",
		      "Content-Type: multipart/form-data;boundary={$boundary}",
		  ),
		);
		
		$ch = curl_init();
		curl_setopt_array($ch, $set);
		$this->data  = curl_exec($ch);
		$this->error = curl_error($ch);
		curl_close($ch);
		return $this->data;
	}
//----------------------------------------------------------------------------
	function exec($type, $url, $data = null, $header = null)
	{		
		$this->config($type, $url, $data);
		
		if($header)
			$this->setheader($header);
		
		$this->dit();
		return $this->data;
	}
//----------------------------------------------------------------------------
	function setopt($k, $v)
	{
		$this->setopt[$k] = $v;
	}
//----------------------------------------------------------------------------
	function post($url, $data, $header = null)
	{
		$this->init();
		return $this->exec('post', $url, $data, $header);
	}
//----------------------------------------------------------------------------
	function get($url, $header = null)
	{		
		$this->init();
		return $this->exec('get', $url, null, $header);
	}
//----------------------------------------------------------------------------
	function flush($set)
	{
		$this->init();
		$this->setopt = $set;
		$this->dit();
		return $this->data;
	}
//----------------------------------------------------------------------------
	protected function init()
	{
		$this->data = '';
		$this->error = '';
		$this->setopt = array();
		$this->cookiefile = ($GLOBALS['DIR_CACHE'] ? $GLOBALS['DIR_CACHE'] : __DIR__) . '/curlcookie.txt';
	}
//----------------------------------------------------------------------------
	protected function setheader($data)
	{
		if(is_string($data) && $data != '')
		{
			$data = trim($data);
			$data = _split("\n", $data);
			array_walk($data, 'trim');
		}
		
		if(is_array($data))
		{
			if($data['ent'] == '')
				$this->setopt[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36';
			else
				$this->setopt[CURLOPT_USERAGENT] = $data['ent'];
			
			if($data['ref'])
				$this->setopt[CURLOPT_REFERER] = $data['ref'];
				
			if($data['cookie'])
			{
				file_put_contents($this->cookiefile, $data['cookie']);
			}
			
			unset($data['ref'], $data['ent'], $data['cookie']);
			
			foreach($data as $k => $v)
			{
				if(is_int($k))
					$this->setopt[CURLOPT_HTTPHEADER][] = $v;
				else
					$this->setopt[CURLOPT_HTTPHEADER][] = "{$k}: {$v}";
			}
		}
	}
//----------------------------------------------------------------------------
	protected function config($type, $url, $postdata = null)
	{		
		if($type == 'get')
		{
			$set = array(
				CURLOPT_TIMEOUT        => $this->timeout,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_SSL_VERIFYHOST => false,
				CURLOPT_URL => $url,
				CURLOPT_HTTPHEADER => array(),
				CURLOPT_COOKIEFILE => $this->cookiefile,
				CURLOPT_COOKIEJAR => $this->cookiefile,
				
			);
		}
		else if($type == 'post')
		{
			if(empty($postdata))
			{
				$postdata = array();
			}
			
			$set = array(
				CURLOPT_TIMEOUT        => $this->timeout,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_SSL_VERIFYHOST => false,
				CURLOPT_URL => $url,
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => $postdata,
				CURLOPT_HTTPHEADER => array(),
			);

			if(is_string($postdata))
			{				
				if($postdata{0} === '{')
					$set[CURLOPT_HTTPHEADER]['Content-Type'] = 'application/json;charset=utf-8';
				else
					$set[CURLOPT_HTTPHEADER]['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
				
				$set[CURLOPT_HTTPHEADER]['Content-Length'] = strlen($postdata);
			}
		}
		
		$this->setopt += $set;
	}
//----------------------------------------------------------------------------
	protected function dit()
	{
		$this->count++;
		$ch = curl_init();
		curl_setopt_array($ch, $this->setopt);
		$this->data  = curl_exec($ch);
		$this->error = curl_error($ch);
		curl_close($ch);
	}
//----------------------------------------------------------------------------
}